import * as THREE from 'three'
import { getWH, loadObj } from '../utils'
import { Camera } from './child/camera'
import { Objs } from './child/object'
import { planeMaterial } from '../materal'
import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'
import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js'
export class Screen {
  constructor(domId) {
    this.domId = domId
    this.raycaster = new THREE.Raycaster()
    this.mouse = new THREE.Vector2()
    // 接收鼠标事件的物体
    this.eventGroup = []
    this.eventMap = []
    this.composer = null
    this.OutlinePass = null
    // 初始化场景
    this.scene = new THREE.Scene()
    // 初始化渲染器
    this.renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true
    })
    this.renderer.setClearColor('rgba(0,0,0,1)')
    const { width, height } = getWH(this.domId)
    this.renderer.setSize(width, height)
    document.getElementById(this.domId).appendChild(this.renderer.domElement)
    // 添加辅助
    this.addHelper()
    // 初始化相机
    this.addCamera()
    // 添加地板
    this.addGround()
    // 添加外边框后期渲染
    this.addOutlinePass()
    // 初始化动画
    this._animate()
  }
  addCamera() {
    const cameraConf = {
      position: { x1: 252.6, y1: 163.5, z1: 174.51 },
      lookAt: { x2: 100, y2: 0, z2: 0 },
      up: { x3: 0, y3: 1, z3: 0 },
      fov: 45, // 摄像机视锥体垂直视野角度
      near: 0.1, // 摄像机视锥体近端面
      far: 5000 // 摄像机视锥体远端面
    }
    const { width, height } = getWH(this.domId)
    this.camera = new Camera(width / height, this.renderer, cameraConf)
  }
  select(selectName) {
    for (const key of Object.keys(this.eventMap)) {
      if (key === selectName) {
        this.eventMap[key].handleSelected()
        this.OutlinePass.selectedObjects = [this.eventMap[key].mesh]
      } else {
        this.eventMap[key].unhandleSelected()
      }
    }
  }
  addHelper() {
    // 添加坐标轴
    // const axes = new THREE.AxesHelper(100)
    // this.scene.add(axes)
    const light = new THREE.AmbientLight(0xffffff) // soft white light
    this.scene.add(light)
    // const size = 1000
    // const divisions = 500
    // const gridHelper = new THREE.GridHelper(size, divisions)
    // this.scene.add(gridHelper)
  }
  async addObj(data) {
    const obj = await loadObj('static/obj/greenhouseW.obj')
    const originObj = obj.children[0]
    // 行列
    const row = 6
    const col = 2
    const rowGap = 50
    const colGap = 100
    for (let j = 0; j < col; j++) {
      for (let i = 0; i < row; i++) {
        const objMap = new Objs(data[row * j + i].name)
        const mesh = objMap.load(originObj.clone(), data[row * j + i])
        if (data[row * j + i].event) {
          // 接收鼠标事件的数组
          this.eventGroup.push(mesh)
          // 建立映射关系
          this.eventMap[data[row * j + i].name] = objMap
        }
        delete data[row * j + i].event
        objMap.addTooltip(data[row * j + i])
        objMap.setPoistion(i * rowGap, 0, -j * colGap)
        this.scene.add(objMap.instance)
      }
    }
    // 默认选中一个
    this.select(this.eventGroup[0].name)
  }
  addGround() {
    const geometry = new THREE.PlaneGeometry(1000, 1000, 32)
    const ground = new THREE.Mesh(geometry, planeMaterial)
    ground.rotation.x = Math.PI / 2
    ground.position.x = -50
    this.scene.add(ground)
  }
  addOutlinePass() {
    const scene = this.scene
    const camera = this.camera.instance
    const renderPass = new RenderPass(scene, camera)
    const { width, height } = getWH(this.domId)
    this.OutlinePass = new OutlinePass(new THREE.Vector2(width, height), scene, camera)
    this.OutlinePass.renderToScreen = true
    this.composer = new EffectComposer(this.renderer)
    this.composer.addPass(renderPass)
    this.composer.addPass(this.OutlinePass)
    // 设置需要添加外边框的网格模型
    // 交互的时候可以设置一个鼠标事件，点击选中了某个模型，就直接把某个网格模型作为值的元素
    // OutlinePass.selectedObjects = [mesh]
    // OutlinePass相关属性设置
    this.OutlinePass.visibleEdgeColor = new THREE.Color(76, 148, 156)
    this.OutlinePass.hiddenEdgeColor = new THREE.Color(0, 1, 0)
    this.OutlinePass.edgeGlow = 1.0
    this.OutlinePass.usePatternTexture = false
    this.OutlinePass.edgeThickness = 2.0
    this.OutlinePass.edgeStrength = 2.0
    this.OutlinePass.downSampleRatio = 2
    this.OutlinePass.pulsePeriod = 0
  }
  // 获取接受鼠标事件的物体
  getEventGroup() {
    return this.eventGroup
  }
  getEventMap() {
    return this.eventMap
  }
  _animate() {
    this.camera.OrbitControls.update()
    requestAnimationFrame(this._animate.bind(this))
    this.composer.render()
    // console.log(this.camera.instance, 'TWEEN.Tween')
    // this.renderer.render(this.scene, this.camera.instance)
  }
  add(obj) {
    this.scene.add(obj)
  }
  remove(obj) {
    this.scene.remove(obj)
  }
}
export class Child extends Screen {
  addCamera() {
    const cameraConf = {
      position: { x1: 44.16, y1: 82.24, z1: 96.47 },
      lookAt: { x2: 4.4, y2: 22.5, z2: 34.9 },
      up: { x3: 0, y3: 1, z3: 0 },
      fov: 45, // 摄像机视锥体垂直视野角度
      near: 0.1, // 摄像机视锥体近端面
      far: 5000 // 摄像机视锥体远端面
    }
    const { width, height } = getWH(this.domId)
    this.camera = new Camera(width / height, this.renderer, cameraConf)
    // 用来确定相机位置
    // setInterval(() => {
    //   console.log(this.camera.OrbitControls.target, 'target')
    //   console.log(this.camera.instance.position, 'position')
    // }, 3000)
  }
  async addObj(data, childData) {
    const obj = await loadObj('static/obj/greenhouse.obj')
    const originObj = obj.children[0]
    // 行列
    const row = 1
    const col = 1
    const rowGap = 50
    const colGap = 100
    for (let j = 0; j < col; j++) {
      for (let i = 0; i < row; i++) {
        const objMap = new Objs(`大棚${row * j + i}`)
        const mesh = objMap.load(originObj.clone(), data[row * j + i])
        // 设置选中效果
        this.OutlinePass.selectedObjects = [mesh]
        objMap.addIOT(this.camera.instance, childData)
        objMap.changeMeshMaterial(0)
        mesh.renderOrder = 1
        // 获取模型长宽高
        // mesh.geometry.computeBoundingBox()
        // console.log(mesh.geometry, 'mesh')
        objMap.setPoistion(i * rowGap, 0, -j * colGap)
        // 接收鼠标事件的数组
        // this.eventGroup.push(mesh)
        this.eventGroup = objMap.eventGroup
        // 建立映射关系
        this.eventMap = objMap.eventMap
        this.scene.add(objMap.instance)
      }
    }
    // this.select(this.eventGroup[0].name)
  }
  select(selectName) {
    for (const key of Object.keys(this.eventMap)) {
      if (key === selectName) {
        // console.log(this.eventMap[key], 'this.eventMap[key]')
        // console.log(this.eventMap[key], 'this.eventMap[key]')
        this.eventMap[key].handleSelected()
        // this.OutlinePass.selectedObjects = [this.eventMap[key].mesh]
      } else {
        this.eventMap[key].unhandleSelected()
      }
    }
  }
}
